package cn.chenxing.module.login.service;

import cn.chenxing.domain.util.DialogBuilderUtil;
import cn.chenxing.domain.util.JFXBaseUtil;
import cn.chenxing.domain.threadlocal.ThreadLocalInfo;
import cn.chenxing.constant.VenusConstant;
import cn.chenxing.module.user.entity.VenusQuestionsListEntity;
import cn.chenxing.module.user.entity.VenusUserInfoEntity;
import cn.chenxing.module.user.service.VenusQuestionsListService;
import cn.chenxing.module.user.service.VenusUserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jfoenix.controls.JFXButton;
import de.felixroske.jfxsupport.AbstractFxmlView;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.Window;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


/**
 * @Description 登录Service层
 * @Author maogen.ymg
 * @Date 2020/2/28 22:17
 */
@Service
@Slf4j
public class LoginService {

    @Resource
    private VenusUserInfoService userInfoService;

    @Resource
    private VenusQuestionsListService questionsListService;

    /**
     * 登录操作
     * @param userInfoEntity 用户信息实体类
     * @return 是否登录成功
     */
    public boolean login(VenusUserInfoEntity userInfoEntity, JFXButton loginButton){
        VenusUserInfoEntity sqlUserInfoEntity = userInfoService.getOne(
                new QueryWrapper<VenusUserInfoEntity>().eq("user_name", userInfoEntity.getUserName()));

        if (sqlUserInfoEntity == null || !sqlUserInfoEntity.getPassword().equals(userInfoEntity.getPassword())) {
            DialogBuilderUtil.showPositiveAlert(loginButton, "请检查!", "账号或密码错误");
            return false;
        }

        return true;
    }

    /**
     * 注册操作
     * @param userInfoEntity 用户信息实体类
     * @return 是否注册成功
     */
    public boolean register(VenusUserInfoEntity userInfoEntity) {
        return userInfoService.save(userInfoEntity);
    }

    /**
     * 忘记密码更新操作
     * @param userInfoEntity 用户信息实体类
     * @return 是否更新成功
     */
    public boolean forgetUpdate(VenusUserInfoEntity userInfoEntity) {
        return userInfoService.updateById(userInfoEntity);
    }

    /**
     * 检查填写内容是否正确（手机号码，密保问题答案）
     * @param userInfoEntity 用户信息实体类
     * @return boolean
     */
    public boolean checkFillCorrectness(VenusUserInfoEntity userInfoEntity){
        VenusUserInfoEntity sqlUserInfoEntity = userInfoService.getOne(
                new QueryWrapper<VenusUserInfoEntity>().eq("user_name", userInfoEntity.getUserName()));

        boolean isPass = sqlUserInfoEntity != null &&
                sqlUserInfoEntity.getMobilePhone().equals(userInfoEntity.getMobilePhone()) &&
                sqlUserInfoEntity.getAnswer().equals(userInfoEntity.getAnswer());
        if(isPass) {
            userInfoEntity.setId(sqlUserInfoEntity.getId());
        }
        return isPass;
    }

    /**
     * 密保问题
     * @return List
     */
    public List<String> getSecurityQuestion() {
        List<VenusQuestionsListEntity> questionsListEntity = questionsListService.list();
        List<String> result = new ArrayList<>();
        for (VenusQuestionsListEntity questionsList : questionsListEntity) {
            result.add(questionsList.getQuestion());
        }
        return result;
    }

    /**
     * 密保问题索引
     * @param question 选择的密保问题
     * @return 索引
     */
    public int getQuestionIndex(String question) {
        List<VenusQuestionsListEntity> questionsListEntity = questionsListService.list();
        int index = 1;
        for (VenusQuestionsListEntity questionsList : questionsListEntity) {
            if (question.equals(questionsList.getQuestion())) {
                index = questionsList.getQuestionIndex();
            }
        }
        return index;
    }

    /**
     * 回到登录界面并关闭当前窗口
     * @param nowWindow 当前窗口
     */
    public void backLoginView(Window nowWindow){
        // 显示登录界面
        Window window = ThreadLocalInfo.get().getPreviousWindow();
        Stage loginStage = (Stage) window;
        loginStage.show();
        // 关闭注册界面
        window = nowWindow;
        Stage stage = (Stage) window;
        stage.close();
    }

    /**
     * 打开fxml主界面窗口 -- 打开主界面窗口(MainScreenBounds) ------无法进行注入，谨慎使用
     * @param fxmlUrl fxml文件位置
     * @throws IOException 读写异常
     */
    public void newStageByFxml(String fxmlUrl) throws IOException {
        Stage stage = new Stage();
        // 设置主界面大小
        JFXBaseUtil.setMainScreenBounds(stage);
        // 读取fxml文件
        FXMLLoader fxmlLoader = new FXMLLoader();
        InputStream in = new ClassPathResource(fxmlUrl).getInputStream();
        Parent root = fxmlLoader.load(in);

        Scene scene = JFXBaseUtil.getDecoratorScene(stage, VenusConstant.MAIN_TITLE, VenusConstant.ICON_URL, root, true);
        stage.setScene(scene);
        in.close();
        stage.show();

    }

    /**
     * 打开View主界面窗口 -- 打开主界面窗口(MainScreenBounds) ------可以注入，推荐使用
     * @param view view
     */
    public void newStageByView(AbstractFxmlView view) {
        Stage stage = new Stage();
        // 设置主界面大小
        JFXBaseUtil.setMainScreenBounds(stage);
        Parent root = view.getView();

        Scene scene = JFXBaseUtil.getDecoratorScene(stage, VenusConstant.MAIN_TITLE, VenusConstant.ICON_URL, root, true);
        stage.setScene(scene);
        stage.show();
    }

    /**
     * view方法打开新窗口 -- 用于注册和忘记密码界面（LoginScreenBounds）
     * @param view AbstractFxmlView
     * @param title 标题(注册/忘记密码)
     * @param window 上一个窗口
     */
    public void newStageByView(AbstractFxmlView view, String title, Window window) {
        Stage stage = new Stage();
        JFXBaseUtil.setLoginScreenBounds(stage);
        Parent root = view.getView();
        Scene scene = JFXBaseUtil.getDecoratorScene(stage, title, VenusConstant.ICON_URL, root, window);
        stage.setScene(scene);
        stage.show();
    }

}
